﻿using PetkaWebDav.Server.Framework.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PetkaWebDav.Server.Framework.BaseClasses
{
    public abstract class DavOptionsBase : DavMethodBase
    {
        /// <summary>
        /// Dav Server OPTIONS Framework Base Class
        /// </summary>
        protected DavOptionsBase()
        {
            this.InternalProcessDavRequest += new DavInternalProcessHandler(DavOptionsBase_InternalProcessDavRequest);
            this.SupportedHttpMethods = HttpMethods.None;
        }

        /// <summary>
        /// WebDav Server Supported Http Methods
        /// </summary>
        protected HttpMethods SupportedHttpMethods { get; set; }


        private int DavOptionsBase_InternalProcessDavRequest(object sender, EventArgs e)
        {
            string _davClass = "1";
            if ((SupportedHttpMethods & HttpMethods.Lock) != 0 && (SupportedHttpMethods & HttpMethods.PropFind) != 0)
                _davClass += ", 2";

            StringBuilder _allowedMethods = new StringBuilder();
            foreach (string enumName in Enum.GetNames(typeof(HttpMethods)))
            {
                if (enumName != "All" && enumName != "None")
                {
                    HttpMethods _httpMethod = (HttpMethods)Enum.Parse(typeof(HttpMethods), enumName, true);

                    if ((SupportedHttpMethods & _httpMethod) != 0)
                    {
                        if (_httpMethod == HttpMethods.VersionControl)
                            _allowedMethods.Append("version-control" + ", ");
                        else
                            _allowedMethods.Append(enumName.ToUpper() + ", ");
                    }
                }
            }

            //Remove the trailing comma [, ]
            if (_allowedMethods.Length > 2)
                _allowedMethods.Remove(_allowedMethods.Length - 2, 2);

            base.HttpApplication.Response.AddHeader("DAV", _davClass);
            base.HttpApplication.Response.AddHeader("Public", _allowedMethods.ToString());
            base.HttpApplication.Response.AddHeader("Allow", _allowedMethods.ToString());
            base.HttpApplication.Response.AddHeader("Accept-Ranges", "bytes");

            return (int)ServerResponseCode.Ok;
        }
    }
}
